//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using SPUserPoll.Business.Components;

namespace SPUserPoll.Presentation.WebParts.UserControls
{   
    public enum SPUserPollAdminMenuType{
        SetupDisplay = 1,
        AnswerDisplay = 2,
        ResultDisplay = 3
    }

    public partial class PollAdminMenu : System.Web.UI.UserControl
    {
        #region globals
        private Control _pollingWebpart = null;

        /// <summary>
        /// Access to the polling webpart
        /// </summary>
        private PollDisplayWebPart PollingWebPart
        {
            get
            {
                if (_pollingWebpart == null)
                    _pollingWebpart = this;

                if (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                {
                    _pollingWebpart = this;
                    while (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                    {
                        _pollingWebpart = _pollingWebpart.Parent;
                    }
                }
                return _pollingWebpart as PollDisplayWebPart;
            }
        }

        /// <summary>
        /// The Id of the Poll
        /// </summary>
        private string PollID
        {
            get { return PollingWebPart.SPUserPollID; }
        }

        /// <summary>
        /// Thd ID of the WebPart
        /// </summary>
        private string WebPartID
        {
            get { return PollingWebPart.ID; }
        }

        /// <summary>
        /// The poll publishing status
        /// </summary>
        private bool PollPublished
        {
            get { return PollingWebPart.SPUserPollPublished; }
        }

        /// <summary>
        /// The closing date of the poll
        /// </summary>
        private DateTime PollClosingDate
        {
            get { return PollingWebPart.SPUserPollClosingDate; }
        }

        private SPUserPollAdminMenuType _menuType = SPUserPollAdminMenuType.SetupDisplay;

        public SPUserPollAdminMenuType MenuType
        {
            get { return _menuType; }
            set { _menuType = value; }
        }
        internal string AnswersListUrl()
        {
            SPList answerList = SPUserPoll.Data.Components.AnswersList.AnswerList();
            string answerFolder = string.Format(@"{0}/{1}", SPContext.Current.Web.Site.ServerRelativeUrl.TrimEnd("/".ToCharArray()), ManageLists.GetAnswerFolderPath(PollID));
            string redirectUrl = string.Format("{0}?RootFolder={1}", answerList.DefaultViewUrl.ToString(), HttpUtility.UrlEncode(answerFolder));
            return redirectUrl;
        }

        internal string ResponsesUrl()
        {
            string listName = ManageLists.GetResponseListName();
            SPList responseList = SPContext.Current.Web.Site.RootWeb.Lists[listName];
            string responseFolder = string.Format(@"{0}/{1}", SPContext.Current.Web.Site.ServerRelativeUrl.TrimEnd("/".ToCharArray()), ManageLists.GetResponseFolderPath(PollID));
            string redirectUrl = string.Format("{0}?RootFolder={1}", responseList.DefaultViewUrl.ToString(), HttpUtility.UrlEncode(responseFolder));
            return redirectUrl;
        }
    #endregion

        /*protected void lbManageResponses_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //list names are limited in length. to get the url we retrieve the list and from that list the url
            string listName = ManageLists.GetResponseListName();
            SPList responseList = SPContext.Current.Web.Site.RootWeb.Lists[listName];
            string responseFolder = string.Format(@"{0}/{1}", SPContext.Current.Web.Site.ServerRelativeUrl.TrimEnd("/".ToCharArray()), ManageLists.GetResponseFolderPath(PollID));
            string redirectUrl = string.Format("{0}?RootFolder={1}", responseList.DefaultViewUrl.ToString(), HttpUtility.UrlEncode(responseFolder));
            //redirect the user to the poll list
            //Response.Redirect(redirectUrl);
        }*/
        /*protected void lbManageAnswers_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //list names are limited in length. to get the url we retrieve the list and from that list the url
            string listName = ManageLists.GetAnswerListName();
            SPList answerList = SPContext.Current.Web.Site.RootWeb.Lists[listName];
            string answerFolder = string.Format(@"{0}/{1}", SPContext.Current.Web.Site.ServerRelativeUrl.TrimEnd("/".ToCharArray()),  ManageLists.GetAnswerFolderPath(PollID));
            string redirectUrl = string.Format("{0}?RootFolder={1}", answerList.DefaultViewUrl.ToString(), HttpUtility.UrlEncode(answerFolder));
            //redirect the user to the poll list
            //Response.Redirect(redirectUrl);
        }*/

        #region event handlers
        protected void Page_Load(object sender, EventArgs e)
        {
            //only show this control if the user has enough rights or is the poll owner           
            if (PollingWebPart.UserIsDesigner == false && PollingWebPart.UserIsOwner == false)
            {
                this.Visible = false;
                return;
            }

            string answerOnclick = string.Format("SPDialog('{0}', 350, 450, 'Manage Poll Answers')", AnswersListUrl());
            string resultsOnclick = string.Format("SPDialog('{0}', 350, 450, 'Manage Responses')", ResponsesUrl());
            lbManageAnswers.Attributes.Add("onclick", answerOnclick);
            lbManageAnswersSecond.Attributes.Add("onclick", answerOnclick);
            lbManageAnswersThird.Attributes.Add("onclick", answerOnclick);

            LinkButton1.Attributes.Add("onclick", resultsOnclick);

            if (MenuType == SPUserPollAdminMenuType.ResultDisplay)
            {
                phResultMenu.Visible = true;
                //Show a expired date to admins if the date has expired
                if (Business.Components.DateAndTime.IsPollExpired(PollClosingDate))
                    litPollExpired.Text = "No votes possible, the closing date has expired)<br/>";

                if (PollingWebPart.SPUserPollResultDisplay != Types.PollResultDisplay.Textual)
                {
                    phChartObjects.Visible = true;
                }
            }

            if (MenuType == SPUserPollAdminMenuType.SetupDisplay)
                phSetupMenu.Visible = true;

            if (MenuType == SPUserPollAdminMenuType.AnswerDisplay)
            {
                phAnswerMenu.Visible = true;
                if (PollingWebPart.SPUserPollHidePreviewResponsesLink == true)
                {
                    lbHideResultLink.Text = "Show the 'view results' link";
                    phShowResults.Visible = true;
                }
            }

            //Add cancel dialog for this button
            lbResetVotes.Attributes.Add("OnClick", "return confirm('All votes for this Poll will be deleted. Are you sure?');");

            if (Page.IsPostBack == false)
            {
                //check if we can show the Publish button We only do it when there are answers available
                if (MenuType == SPUserPollAdminMenuType.SetupDisplay)
                {
                    DateTime zeroDate = new DateTime(2000, 1, 1, 1, 0, 0);

                    //only run this check if the poll has been created
                    if (PollingWebPart.SPUserPollCreationDate != zeroDate && ManageLists.AreAnswersAvailableForPoll(PollID) == true)
                    {
                        phPublishHolder.Visible = true;
                    }
                }
            }
        }

        protected void lbModifyChartSettings_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //show or hide chart settings
            if (phChartSettings.Visible == false)
            {
                if (string.IsNullOrEmpty(txtChartHeight.Text))
                {
                    txtChartHeight.Text = PollingWebPart.SPUserPollChartHeight.ToString();
                    txtChartWidth.Text = PollingWebPart.SPUserPollChartWidth.ToString();
                    chkBackground.Checked = PollingWebPart.SPUserPollShowChartBackground;
                }

                //set the correct items in the dropdowns
                dropdownResultDisplay.SelectedItem.Selected = false;
                dropdownResultType.SelectedItem.Selected = false;
                if (PollingWebPart.SPUserPollResultDisplay != Types.PollResultDisplay.Textual && dropdownResultType.Items.Count == 3)
                    dropdownResultType.Items.Add(new ListItem("None", "3"));

                dropdownResultDisplay.Items[Convert.ToInt32(PollingWebPart.SPUserPollResultDisplay)].Selected = true;
                dropdownResultType.Items[Convert.ToInt32(PollingWebPart.SPUserPollResultType)].Selected = true;

                phChartSettings.Visible = true;
            }
            else
            {
                phChartSettings.Visible = false;
            }
        }

        protected void lbPublishOrUnPublish_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            if (PollPublished == true)
            {
                ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollPublished", false);
                ManageLists.UpdatePollPublicationState(PollID, false);
            }
            else
            {
                ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollPublished", true);
                ManageLists.UpdatePollPublicationState(PollID, true);
            }

            //reload the page for correct display of the webpart
            HttpContext.Current.Response.Redirect(Page.Request.Url.ToString());
        }

        protected void lbResetVotes_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            ManageLists.DeleteVotesForPoll(PollID);

            //reload the page for correct display of the webpart
            HttpContext.Current.Response.Redirect(Page.Request.Url.ToString());

        }

        protected void lbShowOrHideResults_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //Switch the link status
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollHidePreviewResponsesLink", !PollingWebPart.SPUserPollHidePreviewResponsesLink);

            //reload the page for correct display of the webpart
            HttpContext.Current.Response.Redirect(Page.Request.Url.ToString());

        }

        protected void lbShowResults_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //Call the loadresultwebpart function  from the pollanswer control
            ((PollAnswerControl)this.Parent.Parent).LoadResultWebPart();
        }

        protected void lbApplyChartSettings_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //store settings in the webpart
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollResultType", Convert.ToInt32(dropdownResultType.SelectedValue));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollResultDisplay", Convert.ToInt32(dropdownResultDisplay.SelectedValue));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollChartHeight", Convert.ToInt32(txtChartHeight.Text));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollChartWidth", Convert.ToInt32(txtChartWidth.Text));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollShowChartBackground", chkBackground.Checked);

            //reload the page for correct display of the webpart
            HttpContext.Current.Response.Redirect(Page.Request.Url.ToString());

        }

        /// <summary>
        /// Manage none label display option for charts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dropdownResultDisplay_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropdownResultDisplay.SelectedValue != "0")
            {
                if (dropdownResultType.Items.Count == 3)
                {
                    dropdownResultType.Items.Add(new ListItem("None", "3"));
                    dropdownResultType.SelectedItem.Selected = false;
                    dropdownResultType.Items[3].Selected = true;
                    phChartObjects.Visible = true;
                }
            }
            else
            {
                if (dropdownResultType.Items.Count > 3)
                {
                    dropdownResultType.SelectedItem.Selected = false;
                    dropdownResultType.Items.Remove(new ListItem("None", "3"));
                    dropdownResultType.Items[0].Selected = true;
                    phChartObjects.Visible = false;
                }
            }

        }
        #endregion
    }
}